package com.zrwl.poscloud.xo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zrwl.poscloud.base.entity.Message;
import com.zrwl.poscloud.base.entity.MessageModel;
import com.zrwl.poscloud.base.superI.SuperServiceImpl;
import com.zrwl.poscloud.commons.config.message.SmsConfig;
import com.zrwl.poscloud.commons.vo.message.SmsVO;
import com.zrwl.poscloud.xo.mapper.MessageMapper;
import com.zrwl.poscloud.xo.mapper.MessageModelMapper;
import com.zrwl.poscloud.xo.service.MessageModelService;
import com.zrwl.poscloud.xo.service.MessageService;
import com.zrwl.poscloud.xo.service.SmsService;
import com.zrwl.poscloud.xo.service.WxService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class MessageServiceImpl extends SuperServiceImpl<MessageMapper, Message> implements MessageService{
    @Autowired
    SmsConfig smsConfig;
    @Autowired
    SmsService smsService;
    @Autowired
    MessageModelService messageModelService;
    @Autowired
    WxService wxService;
    @Resource
    private MessageMapper messageMapper;

    @Override
    public void sendSms() {
        log.info("开始发送短信：");
        //1.从数据库取到所谓状态为1，平台为2 的message
        log.info("待发送：" + 0 + "条");
        //2.循环发起短信发送，成功的短信状态更新为2，失败的短信状态更新为4，并用计数器进行计数，失败原因更新到result中 to_addr作为手机号
        int success = 0, error = 0;
        try {
            MessageModel model = messageModelService.getConfig(1, 1);
            if (model == null) {
                //未配置对应的消息模板
            }
            //发送模板消息
            SmsVO smsVO = smsService.send("18735536357", model.getCode(), "123##10");
            if (smsVO.isRequestSuccess() && smsVO.isSendSuccess()) {
                success++;
            } else {
                error++;
            }
        } catch (Exception e) {
            e.printStackTrace();
            error++;
        }
        log.info("成功发送：" + success + "条，失败" + error + "条");
    }

    @Override
    public void sendSmsVerifyCode() {
        log.info("开始发送短信验证码：");
        //1.从数据库取到验证码短信
        List<Message> unsentSMSVerifyCode = getUnsentSMSVerifyCode();
        //1.从数据库取到所谓状态为1，平台为2 的message
        log.info("待发送：" + unsentSMSVerifyCode.size() + "条");
        //2.循环发起短信发送，成功的短信状态更新为2，失败的短信状态更新为4，并用计数器进行计数，失败原因更新到result中 to_addr作为手机号
        int success = 0, error = 0;
        try {
            MessageModel model = messageModelService.getConfig(1, 1);
            if (model == null) {
                //未配置对应的消息模板
                log.info("未配置对应的消息模板");
                error++;
            }else {
                for (Message message : unsentSMSVerifyCode) {
                    //发送模板消息
                    SmsVO smsVO = smsService.send(message.getTelephone(), model.getCode(), message.getContent());
                    if (smsVO.isRequestSuccess() && smsVO.isSendSuccess()) {
                        message.setStatus(2);
                        message.setSendTime(new Date());
                        success++;
                    } else {
                        message.setStatus(4);
                        error++;
                    }
                    //成功的短信状态更新为2，失败的短信状态更新为4
                    messageMapper.updateSMSStatus(message.getStatus(), message.getUid(), message.getSendTime());
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            error++;
        }
        log.info("成功发送：" + success + "条，失败" + error + "条");

    }

    @Override
    public void sendWx() {
        try {
            wxService.sendTemplateInfo("obYcz6g4B52onGF1Qh8n2K9PRzYM", "enWLs4pr_XwlF0raEwnT-g1gGHINEF069pW_GIIcOiw", "http://wx.yucard.cn",
                    "您的本期账单已产生，请仔细核对！",
                    "查看详情可以设置是否继 续接收此类消息",
                    "2021年2月份一卡通账单,2021年3月1日,20000.50");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<Message> getUnsentSMSVerifyCode() {
        //获取未过期的短信验证码
        List<Message> unexpiredSMSVerifyCode = messageMapper.getUnexpiredSMSVerifyCode();
        //获取未发送的短信验证码
        return messageMapper.getUnsentSMSVerifyCode(unexpiredSMSVerifyCode);
    }

    @Override
    public void sendMessage(int plant, int type) {
        log.info("开始发送消息：");
        MessageModel model = messageModelService.getConfig(plant, type);
        //1.从数据库取到未发送的消息
        List<Message> notSentMessage = null;
        if (model == null) {
            //未配置对应的消息模板
            log.info("未配置对应的消息模板");
        }else {
            int success = 0, error = 0;
            switch (plant) {
                case 1://短信
                    notSentMessage = messageMapper.getUnsentTextMessages(model.getType());
                    if (notSentMessage == null || notSentMessage.size() == 0) {
                        log.info("暂无消息");
                        error++;
                    }else {
                        Message messageSMS = notSentMessage.get(0);
                        try {
                            //发送短信消息
                            SmsVO smsVO = smsService.send(messageSMS.getTelephone(), model.getCode(), messageSMS.getContent());
                            if (smsVO.isRequestSuccess() && smsVO.isSendSuccess()) {
                                messageSMS.setStatus(2);
                                messageSMS.setSendTime(new Date());
                                success++;
                            } else {
                                messageSMS.setStatus(4);
                                error++;
                            }
                            //成功的短信状态更新为2，失败的短信状态更新为4
                            messageMapper.updateSMSStatus(messageSMS.getStatus(), messageSMS.getUid(), messageSMS.getSendTime());
                        } catch (Exception e) {
                            e.printStackTrace();
                            error++;
                        }
                    }
                    log.info("成功发送：" + success + "条，失败" + error + "条");
                    break;
                case 2://微信
                    notSentMessage = messageMapper.getNotSentWechatMessage(model.getCode());
                    if (notSentMessage == null || notSentMessage.size() == 0) {
                        log.info("暂无消息");
                        error++;
                    }else {
                        Message messageWX = notSentMessage.get(0);
                        try {
                            //发送微信消息
                            String backStr = wxService.sendTemplateInfo(messageWX.getOpenId(), messageWX.getTemplateId(), messageWX.getUrl(), messageWX.getFirst(), messageWX.getRemark(), messageWX.getContent());
                            JSONObject result = JSONObject.parseObject(backStr);
                            if (result.getString("errmsg").equals("ok")) {
                                messageWX.setStatus(2);
                                messageWX.setSendTime(new Date());
                                success++;
                            } else {
                                messageWX.setStatus(4);
                                error++;
                            }
                            //成功的微信状态更新为2，失败的微信状态更新为4
                            messageMapper.updateWXStatus(messageWX.getStatus(), messageWX.getUid(), messageWX.getSendTime());
                        } catch (Exception e) {
                            e.printStackTrace();
                            error++;
                        }
                    }
                    log.info("成功发送：" + success + "条，失败" + error + "条");
                    break;
            }
        }
    }

    @Override
    public void sendWXAccountBalanceTasks() {
        log.info("开始发送余额不足提醒微信消息：");
        MessageModel model = messageModelService.getConfig(2, 2);
        int success = 0, error = 0;
        if (model == null) {
            //未配置对应的消息模板
            log.info("未配置对应的消息模板");
            error++;
        }else {
            //1.从数据库取到未发送余额不足提醒微信消息
            List<Message> notSentWechatMessage = messageMapper.getNotSentWechatMessage(model.getCode());
            //2.循环发起微信发送，成功的微信状态更新为2，失败的微信状态更新为4，并用计数器进行计数，失败原因更新到result中
            try {
                if (notSentWechatMessage == null) {
                    //未配置对应的消息模板
                    log.info("暂无消息");
                    error++;
                }else {
                    Message message = notSentWechatMessage.get(0);
                    //发送微信消息
                    String backStr = wxService.sendTemplateInfo(message.getOpenId(), message.getTemplateId(), message.getUrl(), message.getFirst(), message.getRemark(), message.getContent());
                    JSONObject result = JSONObject.parseObject(backStr);
                    if (result.getString("errmsg").equals("ok")) {
                        message.setStatus(2);
                        message.setSendTime(new Date());
                        success++;
                    } else {
                        message.setStatus(4);
                        error++;
                    }
                    //成功的微信状态更新为2，失败的微信状态更新为4
                    messageMapper.updateWXStatus(message.getStatus(), message.getUid(), message.getSendTime());
                }
            } catch (Exception e) {
                e.printStackTrace();
                error++;
            }
        }
        log.info("成功发送：" + success + "条，失败" + error + "条");
    }
}
